let aimess = '';
$(document).ready(function () {
    var chat = {
        messageToSend: '',
        messageResponses: [
            'Why did the web developer leave the restaurant? Because of the table layout.',
            'How do you comfort a JavaScript bug? You console it.',
            'An SQL query enters a bar, approaches two tables and asks: "May I join you?"',
            'What is the most used language in programming? Profanity.',
            'What is the object-oriented way to become wealthy? Inheritance.',
            'An SEO expert walks into a bar, bars, pub, tavern, public house, Irish pub, drinks, beer, alcohol'
        ],
        init: function () {
            this.cacheDOM();
            this.bindEvents();
            this.render();
        },
        cacheDOM: function () {
            this.$chatHistory = $('.chat-history');
            this.$button = $('#send');
            this.$textarea = $('#message-to-send');
            this.$chatHistoryList = this.$chatHistory.find('ul');
        },
        bindEvents: function () {
            this.$button.on('click', this.addMessage.bind(this));
            this.$textarea.on('keyup', this.addMessageEnter.bind(this));
        },
        render: async function () {
            this.scrollToBottom();
            if (this.messageToSend.trim() !== '') {
                var condic = {'context': this.messageToSend}

                // responses
                var templateResponse = Handlebars.compile($("#message-response-template").html());
                // var res = this.getRandomItem(this.messageResponses, condic)
                await $.get("aiLinkView", condic, function (date) {
                    if (date['status'] === '200') {
                        aimess = date['content']
                    } else {
                        aimess = '抱歉,我生病了,不能回复你'
                    }
                })

                var res = aimess
                var contextResponse = {
                    response: res,
                    time: this.getCurrentTime()
                };
                //删除思考中
                var obj = document.getElementById('sikao')
                obj.remove()
                this.$chatHistoryList.append(templateResponse(contextResponse));
                this.scrollToBottom();

            }
        },

        addMessage: function () {
            this.messageToSend = this.$textarea.val()
            this.myadd();
            var templateResponse = Handlebars.compile($("#message-response-template-wait").html());
            var res = ''
            var contextResponse = {
                response: res,
                time: this.getCurrentTime()
            };

            this.$chatHistoryList.append(templateResponse(contextResponse));
            this.scrollToBottom();

            setTimeout(function () {/*异步执行,先添加用户发言,再思考,再发送*/
                this.render();
            }.bind(this), 500);

        },
        addMessageEnter: function (event) {
            // enter was pressed
            if (event.keyCode === 13) {
                this.addMessage();
            }
        },
        myadd: function () {
            this.scrollToBottom();
            if (this.messageToSend.trim() !== '') {
                var template = Handlebars.compile($("#message-template").html());
                var context = {messageOutput: this.messageToSend, time: this.getCurrentTime()};

                this.$chatHistoryList.append(template(context));
                this.scrollToBottom();
                this.$textarea.val('');
            }
        },
        scrollToBottom: function () {
            this.$chatHistory.scrollTop(this.$chatHistory[0].scrollHeight);
        },
        getCurrentTime: function () {
            return new Date().toLocaleTimeString().replace(/([\d]+:[\d]{2})(:[\d]{2})(.*)/, "$1$3");
        },
        getRandomItem: function (arr, condic) {
            getAiLink(condic);
            return aimess;
        }

    };

    chat.init();

    var searchFilter = {
        options: {valueNames: ['name']},
        init: function () {
            var userList = new List('people-list', this.options);
            var noItems = $('<li id="no-items-found">No items found</li>');

            userList.on('updated', function (list) {
                if (list.matchingItems.length === 0) {
                    $(list.list).append(noItems);
                } else {
                    noItems.detach();
                }
            });
        }
    };

    searchFilter.init();

});

function getAiLink(dic) {
    // $.ajaxSettings.async = false
    $.get("aiLinkView", dic, function (date) {
        // str = date.toString();
        if (date['status'] === '200') {
            aimess = date['content']
        } else {
            aimess = '抱歉,我生病了,不能回复你'
        }
        // str = JSON.stringify(date)
    })
    // $.ajaxSettings.async = true;
    return aimess
}



